import socket
import os
import sys
import signal

import logging
import logging.config
import logging.handlers

def signal_handler(signum, frame):
    sys.exit(0)

if __name__ == '__main__':
    try:
            pid = os.fork()
            if pid > 0:
                    sys.exit(0)
    except OSError, e:
            print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
            sys.exit(1)

    # decouple from parent environment 
    ##os.chdir("/")   
    exe_path = sys.argv[0]
    os.chdir(os.path.dirname(os.path.abspath(exe_path)))

    os.setsid()
    os.umask(0)

    # do second fork  
    try:
            pid = os.fork()
            if pid > 0:
                    # exit from second parent, print eventual PID before  
                    sys.exit(0)
    except OSError, e:
            print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
            sys.exit(1)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    logging.config.fileConfig("log.conf")
    lg = logging.getLogger("logs")

    HOST="localhost"
    PORT=5566

    service = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    service.bind(("", PORT))

    while 1:
        # serve forever
        data, client = service.recvfrom(1024)
        if data[-1:] == '\n':
            data = data[0:-1]
        lg.info("[" + client[0] + "]:" + data)

